<?php
# @version SVN: $Id: tree.php 592 2012-06-06 21:02:45Z novachok $

# MOVE NODE BACKEND
if($REQUEST->getRequestLast() == 'move')
{
   $e = FALSE;
   $node_patern = '/^(c|a|n)?\d+$/';
   if(!empty($_POST['node']) && preg_match($node_patern, $_POST['node']))
   {
      $node_type = substr($_POST['node'], 0, 1);
      $node_id   = substr($_POST['node'], 1);
   } else
   {
      $e = TRUE;
   }
   if(!empty($_POST['parent']) && preg_match($node_patern, $_POST['parent']))
   {
      $parent_type = substr($_POST['parent'], 0, 1);
      $parent_id   = substr($_POST['parent'], 1);
   } else
   {
      $e = TRUE;
   }
   if(!empty($_POST['relate']) && preg_match($node_patern, $_POST['relate']))
   {
      $relate_type = substr($_POST['relate'], 0, 1);
      $relate_id   = substr($_POST['relate'], 1);
   } else
   {
      $e = TRUE;
   }
   $position = !empty($_POST['position']) && in_array($_POST['position'], array('after', 'before', 'inside', 'first', 'last')) ? $_POST['position'] : FALSE;

   if(!empty($position) && !$e)
   {
      // TODO: при премещении статьи призрака (по бинду) - перемещать не статью - а изменять ее бинд
      if($node_type == 'a' && $node_type == $relate_type)
      {
         # UPDATE ARTICLE POSITION BETWEEN OTHER ARTICLES
         $DB->sql = 'SELECT `position` FROM `meccano_articles` WHERE `id` = "'. $relate_id .'"';
         $DB->DB_Query();
         $p = $DB->DB_GetResult();
         if($position == 'after') $p++;
         $DB->DB_StartTransaction();
         $DB->sql = 'UPDATE `meccano_articles` SET `position` = `position` + 1 WHERE `position` >= "'. $p .'" AND `cat` = "'. $parent_id .'" ORDER BY `position` ASC';
         $DB->DB_Query();
         $DB->sql = 'UPDATE `meccano_articles` SET `position` = "'. $p .'", `cat` = "'. $parent_id .'" WHERE `id` = "'. $node_id .'"';
         $DB->DB_Query();
         $e = $DB->DB_EndTransaction();
      } elseif($node_type == 'a' && $position == 'inside' && $relate_type == 'c')
      {
         # UPDATE ARTICLE CATEGORY AFTER MOVING INTO EMPTY FOLDER
         $DB->DB_StartTransaction();
         $DB->sql = 'UPDATE `meccano_articles` SET `position` = `position` + 1 WHERE `cat` = "'. $parent_id .'"';
         $DB->DB_Query();
         $DB->sql = 'UPDATE `meccano_articles` SET `position` = 1, `cat` = "'. $parent_id .'" WHERE `id` = "'. $node_id .'"';
         $DB->DB_Query();
         $e = $DB->DB_EndTransaction();
      } elseif($node_type == 'c')
      {
         # MOVE NODE
         $node_positions = array('parent'=>$parent_id, 'after'=>NULL, 'before'=>NULL, 'last'=>FALSE);
         if($position == 'inside')
         {
            $node_positions['after'] = $parent_id;
         } elseif($position == 'after' && $relate_type == 'c')
         {
            $node_positions['after'] = $relate_id;
         } elseif($position == 'before' && $relate_type == 'c')
         {
            $node_positions['before'] = $relate_id;
         } else
         {
            $node_positions['after'] = $parent_id;
            $node_positions['last']  = TRUE;
         }

         $e = $TREE->moveNode($node_id, $node_positions);
      }
   } else
   {
      $e = FALSE;
   }
   echo json_encode($e);
   exit();
}


# DELETE TREE NODE OR ARTICLE
if($REQUEST->getRequestLast() == 'delete')
{
   $respond = FALSE;
   if(!empty($_POST['type']) && !empty($id))
   {
      if($_POST['type'] == 'a')
      {
         $DB->sql = 'UPDATE `meccano_articles` SET `deleted` = NOW() WHERE `id` = ' . $id;
         $DB->DB_Query();

         if(config::read('search','enabled'))
         {
            $SEARCH = new search();
            $SEARCH->deleteArticle($id);
         }

         $respond = $DB->DB_GetAffected();
      } elseif($_POST['type'] == 'c')
      {
         $respond = $TREE->deleteNode($id);
      }
   }

   echo json_encode($respond);
   exit();
}


if(!empty($id))
{
   $nodes = $TREE->getTree($id)->childs;
} else
{
   $nodes = $TREE->getTree();
}

# CLEAR TREE FROM SYSTEM CATEGORIES FOR NOT ROOT USERS
if(session::user() && session::user()->id != 1 && !empty($nodes))
{
   $tmp = array();
   foreach($nodes AS $n)
   {
      if($n->system == FALSE)
      {
         $tmp[$n->id] = $n;
      }
   }

   $nodes = $tmp;
   unset($tmp);
}


# CALCULATE ARTICLES UNDER NODES
$exists_articles = array();
if($nodes || $id)
{
   $nodes_id = array();
   if($nodes) $nodes_id = array_merge($nodes_id, array_keys($nodes));
   if($id) array_unshift($nodes_id, $id);
   $nodes_id = array_filter($nodes_id, 'is_numeric');
   
   $sql = 'SELECT COUNT(*) AS `c`, `cat` AS `n`
      FROM `meccano_articles`
      WHERE `deleted` IS NULL AND `cat` IN ('. join(',', $nodes_id) .')
      GROUP BY `cat`';
   
   if(config::read('fetch_bind_articles', 'system'))
   {
      $sql = '('. $sql .') UNION (
         SELECT COUNT(*) AS `c`, b.bind AS `n`
         FROM meccano_articles AS a
         JOIN meccano_binds AS b ON a.id = b.node
         WHERE a.deleted IS NULL 
            AND b.bind IN (500,501,502) 
            AND b.bind_belong = "c"
         GROUP BY b.bind)';
   }
   
   $DB->sql = $sql;
   $fetched = $DB->DB_Fetch();
   for($i=0,$t=sizeof($fetched); $i<$t; $i++)
   {
      if(!isset($exists_articles[$fetched[$i]['n']])) $exists_articles[$fetched[$i]['n']] = 0;
      $exists_articles[$fetched[$i]['n']] += $fetched[$i]['c'];
   }
}

# GET ARTICLES ASSOCIATED WITH A NODE
$articles_list = array();
if($id)
{
   if(config::read('fetch_bind_articles', 'system'))
   {
      $sql = 'SELECT a.id, a.cat, t.title, a.active 
         FROM `meccano_articles` AS a
         JOIN meccano_articles_translate AS t ON a.id = t.id AND t.lang = '. $REQUEST->getLangDefaultId() .'
         WHERE (a.cat = '. $id .' OR a.id IN (SELECT node FROM meccano_binds WHERE bind_belong = "c" AND bind = '. $id .'))
            AND a.deleted IS NULL
         ORDER BY a.`position` ASC
         LIMIT 0, '. config::read('items', 'system');
   } else {
      $sql = 'SELECT DISTINCT a.id, a.cat, t.title, a.active, "" AS bind 
         FROM meccano_articles AS a, meccano_articles_translate AS t 
         WHERE a.deleted IS NULL 
            AND a.`cat` = '. $id .'
            AND a.deleted IS NULL
            AND a.id = t.id 
            AND t.`lang` = '. $REQUEST->getLangDefaultId() .' 
         ORDER BY a.`position` ASC
         LIMIT 0, '. config::read('items', 'system');
   }
   
   $DB->sql = $sql;
   $articles_list = $DB->DB_Fetch();
}

$startups = getDirList(ROOT . '/engine');
$startups = $startups['file'];

$jsonString = array();

$i = 0;
if(!empty($nodes))
{
   # BUILD INIT JSON FOR TREE
  // {"attr":{"id":"node_3","rel":"default"},"data":"ff","state":"closed"}
   foreach($nodes AS $n)
   {
      $jsonString[$i]['attr']['id']  = 'c'. $n->id;
      $jsonString[$i]['attr']['rel'] = 'folder';
      //var_dump($n->active); continue;
      if($n->active == 0)
      {
         $jsonString[$i]['attr']['rel'] .= '-del';
      } elseif(in_array($n->alias . '.inc', $startups) || in_array($n->alias . '.global.inc', $startups))
      {
         $jsonString[$i]['attr']['rel'] .= '-exe';
      }
      $jsonString[$i]['data']['title']          = $n->title;
      $jsonString[$i]['data']['attr']['target'] = 'content';
      $jsonString[$i]['data']['attr']['title']  = $n->id .' | '. $n->alias;
      $jsonString[$i]['data']['attr']['href']   = '/admin/category/'. $n->id .'.html';
      if(!empty($n->childs) || isset($exists_articles[$n->id]))
      {
         $jsonString[$i]['state'] = 'closed';
      } else
      {
         $jsonString[$i]['attr']['rel'] .= '-empty';
      }
      ++$i;
   }
}

if(!empty($articles_list))
{
   foreach($articles_list AS $a)
   {
      $jsonString[$i]['attr']['id']             = 'a'. $a['id'];
      $jsonString[$i]['attr']['rel']            = ($id != $a['cat'] ? 'article-binded' : ($a['active'] == 1 ? 'article' : 'article-del'));
      $jsonString[$i]['data']['title']          = '('. $a['id'] .') '. $a['title'];
      $jsonString[$i]['data']['attr']['target'] = 'content';
      $jsonString[$i]['data']['attr']['title']  = $a['title'];
      $jsonString[$i]['data']['attr']['href']   = '/admin/article/'. $a['id'] .'.html';
      ++$i;
   }
   
   if(!empty($exists_articles[$id]) && $exists_articles[$id] > config::read('items', 'system'))
   {
      $jsonString[] = array(
         'attr' => array(
            'id'  => 'c'. $id,
            'rel' => 'article-more'
         ),
         'data' => array(
            'title'  => gettext::translate('meccano', 'more_articles'),
            'attr' => array(
               'target' => 'content',
               'title'  => gettext::translate('meccano', 'more_articles'),
               'href'   => '/admin/category/'. $id .'#t_fields_a'
            )
         )
      );
   }
}

$jsonString = json_encode($jsonString);

if($id !== FALSE)
{
   echo $jsonString;
   exit();
}

$SMARTY->assign('jsonString', $jsonString);

$layout = 'tree.html';


/* * ***********************************************************
 *                      FUNCTIONS                            *
 * *********************************************************** */

function PrepareTree($tree, &$articles, $startups = array())
{
   $composed = array();
   if (is_array($tree) && count($tree) > 0)
   {
      foreach ($tree AS $node)
      {
         $tmp['id'] = $node['id'];
         $tmp['folder'] = true;
         $tmp['system'] = $node['system'];
         $tmp['parent'] = $node['parent'];
         $tmp['active'] = $node['active'];
         $tmp['alias'] = $node['alias'];
         $tmp['title'] = $node['title'];
         $tmp['startup'] = in_array($node['alias'] . '.inc', $startups) ? 1 : (in_array($node['alias'] . '.global.inc', $startups) ? 1 : 0);
         $tmp['childs'] = array();

         if (count($node['childs']) > 0)
         {
            $tmp['childs'] = array_merge($tmp['childs'], PrepareTree($node['childs'], $articles, $startups));
         }

         $article_childs = array();
         if (isset($articles[$node['id']]) && count($articles[$node['id']]) > 0)
         {
            foreach ($articles[$node['id']] AS $article)
            {
               $tmp_a['id'] = (int) $article['id'];
               $tmp_a['folder'] = false;
               $tmp_a['parent'] = (int) $node['id'];
               $tmp_a['active'] = $article['active'];
               $tmp_a['alias'] = '';
               $tmp_a['title'] = $article['title'];
               $tmp_a['position'] = (int) $article['position'];
               $tmp_a['childs'] = array();

               $article_childs[] = $tmp_a;
               unset($articles[$node['id']]);
            }

            $tmp['childs'] = array_merge($tmp['childs'], $article_childs);
         }
         unset($articles[$node['id']]);

         $composed[] = $tmp;
      }
   }

   return $composed;
}